<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch">
      <el-form-item label="库房名称" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择库房名称" clearable style="width: 300px" maxlength="30">
          <el-option v-for="item in storeNameOption" :key="item.value" :label="item.label" :value="item.value" style="width: 300px">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库房管理员" prop="manager">
        <el-select v-model="queryParams.manager" clearable placeholder="请选择" style="width: 300px">
          <el-option v-for="item in userOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="入库时间" prop="dateRange">
        <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable style="width: 300px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出库时间" prop="dateRange1">
        <el-date-picker v-model="dateRange1" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable style="width: 300px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入来访人员或来访人员信息或来访目的或库房接待人员" clearable style="width: 490px" maxlength="30"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button style="margin-left: 20px" type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd" v-hasPermi="['archive:warehouseManagement:PersonnelAccess:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete"  @click="handlePlDelete" v-hasPermi="['archive:warehouseManagement:PersonnelAccess:delete']">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download"  @click="handleExport" v-hasPermi="['archive:warehouseManagement:PersonnelAccess:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-printer"  @click="handlePrint" v-hasPermi="['archive:warehouseManagement:PersonnelAccess:print']">打印</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="table" v-loading="loading" :data="personnelList" :height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="id"/>
      <el-table-column label="库房名称" prop="storeName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="库房管理员" prop="manager" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="入库时间" prop="inTime" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="出库时间" prop="outTime" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="来访人员" prop="comeUser" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="来访人员信息" prop="userInfo" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="来访目的" prop="muDi" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="库房接待人员" prop="jieDai" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button  type="text" icon="el-icon-view" @click="handleView(scope.row)" v-hasPermi="['archive:warehouseManagement:PersonnelAccess:detail']">详情</el-button>
          <el-button  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['archive:warehouseManagement:PersonnelAccess:edit']">修改</el-button>
          <el-button  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['archive:warehouseManagement:PersonnelAccess:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加、修改人员出入库 -->
    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
      <el-form ref="personnelForm" :model="personnelForm" :rules="personnelRules" label-width="120px" :disabled="isShowView">
        <el-row>
          <el-col :span="12">
            <el-form-item label="库房名称" prop="storeId">
              <el-select v-model="personnelForm.storeId" placeholder="请选择库房名称" clearable style="width: 300px" @input="changeStoreName">
                <el-option v-for="item in storeNameOption" :key="item.value" :label="item.label" :value="item.value" style="width: 300px"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库房管理员" prop="manager">
              <el-select v-model="personnelForm.manager" clearable placeholder="请选择" style="width: 300px">
                <el-option v-for="item in managerOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库时间" prop="inTime">
              <el-date-picker v-model="personnelForm.inTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库时间" prop="outTime">
              <el-date-picker v-model="personnelForm.outTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="来访人员" prop="comeUser">
              <el-input v-model="personnelForm.comeUser" placeholder="请输入来访人员" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来访人员信息" prop="userInfo">
              <el-input v-model="personnelForm.userInfo" placeholder="来访人员信息" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="来访目的" prop="muDi">
              <el-input v-model="personnelForm.muDi" placeholder="请输入来访目的" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库房接待人员" prop="jieDai">
              <el-input v-model="personnelForm.jieDai" placeholder="请输入库房接待人员" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="personnelForm.remark" type="textarea" :rows="2" placeholder="请输入内容" ref="textareaRef" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-show="isShow" @click="submitForm">保 存</el-button>
        <el-button  @click="personnelCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打印 -->
    <print :printOpen="printOpen" @printCancel="printCancel" ref="printRef" :printTitle="printTitle"></print>

  </div>
</template>

<script>
import estimateTableHeight from '@/mixins/estimateTableHeight'
import print from "@/views/archive/warehouseManagement/print.vue";
import {
  addPerson, deletePerson,
  getPersonDetail,
  getStoreName,
  list,
  storeList, updatePerson
} from "@/api/archive/warehouseManagement/personnelAccess.js";
import {userList} from "@/api/archive/warehouseManagement/warehouseInformation.js";
export default {
  name: "index",
  mixins: [estimateTableHeight], // 混入方法
  components: {
    print
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum:1,
        pageSize:10,
        storeId: undefined,
        keyword: undefined,
        manager: undefined
      },
      dateRange: [],
      dateRange1: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员出入库表格数据
      personnelList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹出层表单
      personnelForm: {},
      // 弹出层表单校验
      personnelRules: {
        storeId: [
          { required: true, message: "库房名称不能为空" }
        ],
        manager: [
          { required: true, message: "库房管理员不能为空" }
        ],
        inTime: [
          { required: true, message: "入库时间不能为空", trigger: "blur" }
        ],
        outTime: [
          { required: true, message: "出库时间不能为空", trigger: "blur" }
        ],
        comeUser: [
          { required: true, message: "来访人员不能为空", trigger: "blur" }
        ],
        userInfo: [
          { required: true, message: "来访人员信息不能为空", trigger: "blur" }
        ],
        muDi: [
          { required: true, message: "来访目的不能为空", trigger: "blur" }
        ]
      },
      // 库房名称下拉框
      storeNameOption: [],
      // 库房管理员下拉框
      userOption: [],
      // 新增库房管理员下拉框
      managerOption: [],
      // 是否禁用
      isShowView: false,
      // 是否展示
      isShow: true,
      // 是否显示打印弹出窗
      printOpen: false,
      // 标题
      printTitle: "人员出入库记录表"
    }
  },
  created() {
    this.getOption()
    this.getList()
  },
  methods: {
    // 获取下拉框
    getOption() {
      storeList().then(response => {
        this.storeNameOption = response.rows.map(item =>{
          return {
            value: item.storeId,
            label: item.storeName
          }
        })
      })

      userList().then(response => {
        this.userOption = response.rows.map(item =>{
          return {
            value: item.userId,
            label: item.userName
          }
        })
      })
    },
    // 改变库房名称时 获取库房管理员下拉框
    changeStoreName() {
      console.log(this.personnelForm.storeId)
      this.form = {
        storeId: this.personnelForm.storeId
      }
      getStoreName(this.form).then(response => {
        this.managerOption = response.rows.map(item =>{
          return {
            value: item.userId,
            label: item.userName
          }
        })
      })
    },
    table_index(index){
      return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.dateRange != null) {
        if (this.dateRange.length != 0) {
          this.queryParams.inTime = this.dateRange[0].toString()
          this.queryParams.edInTime = this.dateRange[1].toString()
        }
      }
      if(this.dateRange1 != null) {
        if (this.dateRange1.length != 0) {
          this.queryParams.outTime = this.dateRange1[0].toString()
          this.queryParams.edOutTime = this.dateRange1[1].toString()
        }
      }
      this.getList();
      this.queryParams.inTime = ""
      this.queryParams.edInTime = ""
      this.queryParams.outTime = ""
      this.queryParams.edOutTime = ""
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.dateRange1 = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 获取表格数据
    getList() {
      this.loading = true
      list(this.queryParams).then(response => {
        this.personnelList = response.rows
        for (let i = 0; i < response.rows.length; i++) {
          // 渲染表格数据
          for (let j = 0; j < this.userOption.length; j++) {
            if(response.rows[i].manager == this.userOption[j].value){
              this.personnelList[i].manager = this.userOption[j].label
            }
          }
        }
        this.total = response.total
        this.loading = false
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 新增
    handleAdd() {
      this.reset()
      this.resetForm('personnelForm')
      this.isShowView = false
      this.isShow = true
      this.title = "新增信息"
      this.open = true
    },
    // 批量删除
    handlePlDelete(row) {
      const ids = row.id || this.ids;
      if (ids.length !== 0) {
        this.$modal.confirm('是否确认删除数据？').then(function () {
          return deletePerson(ids)
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      } else {
        this.$modal.msgError("请选择要删除的数据");
      }
    },
    // 导出
    handleExport(row) {
      const ids = row.id || this.ids;
      if(ids.length != 0) {
        this.queryParams.ids=ids.toString();
      }
      this.download('/archive/personnelEntryExit/export', {
        ...this.queryParams
      }, `personnelAccess_${new Date().getTime()}.xlsx`)
      this.queryParams.ids = ""
    },
    // 打印
    handlePrint(row) {
      const ids = row.id || this.ids;
      if(ids.length > 1) {
        this.$modal.msgError("请选择一条数据")
      } else if (ids.length !== 0) {
        // const columns = this.$refs.table.columns;
        // const labels = columns.map(column => column.label);
        // var filteredLabels = labels.slice(2)
        // filteredLabels = filteredLabels.slice(0, filteredLabels.length-1)
        // console.log(filteredLabels);
        getPersonDetail(ids).then(response =>{
          const form = [
            [
              { value: "库房名称", colspan: 1, rowspan: 1 },
              { value: response.data.storeName, colspan: 3, rowspan: 1 }
            ],
            [
              { value: "来访人员", colspan: 1, rowspan: 1 },
              { value: response.data.comeUser, colspan: 3, rowspan: 1 }
            ],
            [
              { value: "入库时间", colspan: 1, rowspan: 1 },
              { value: response.data.inTime, colspan: 1, rowspan: 1 },
              { value: "出库时间", colspan: 1, rowspan: 1 },
              { value: response.data.outTime, colspan: 1, rowspan: 1 }
            ],
            [
              { value: "人员信息记录", colspan: 1, rowspan: 2 },
              { value: "登记信息", colspan: 3, rowspan: 1 }
            ],
            [
              { value: "来访目的："+response.data.muDi, colspan: 2, rowspan: 1 },
              { value: "来访人员信息："+response.data.userInfo, colspan: 1, rowspan: 1 }
            ],
            [
              { value: "库房接待", colspan: 1, rowspan: 1 },
              { value: response.data.jieDai, colspan: 3, rowspan: 1 }
            ],
            [
              { value: "填表人（签名）", colspan: 1, rowspan: 1, style:"height: 4em; line-height: 4em;" },
              { value: "年   月   日", colspan: 2, rowspan: 1, style:"text-align: right;padding-top: 5%;right: 0px; white-space: pre-wrap" },
              { value: "年   月   日", colspan: 1, rowspan: 1, style:"text-align: right;padding-top: 5%;right: 0px; white-space: pre-wrap" }
            ],
            [
              { value: "审核人（签名）", colspan: 1, rowspan: 1, style:"height: 4em; line-height: 4em;" },
              { value: "年   月   日", colspan: 2, rowspan: 1, style:"text-align: right;padding-top: 5%;right: 0px; white-space: pre-wrap" },
              { value: "年   月   日", colspan: 1, rowspan: 1, style:"text-align: right;padding-top: 5%;right: 0px; white-space: pre-wrap" }
            ],
            [
              { value: "单位（印章）", colspan: 1, rowspan: 1, style:"height: 4em; line-height: 4em;" },
              { value: "年   月   日", colspan: 2, rowspan: 1, style:"position: relative;text-align: right;padding-top: 5%;right: 0px; white-space: pre-wrap" },
              { value: "年   月   日", colspan: 1, rowspan: 1, style:"position: relative;text-align: right;padding-top: 5%;right: 0px; white-space: pre-wrap" }
            ],
          ];
          this.printOpen = true
          this.$nextTick(() => {   //此函数执行时所有的DOM挂载和渲染都已完成
            this.$refs.printRef.init(form,this.printTitle);     //获取子组件中init方法并将父组件数据传递给子组件
          });
        })
      } else {
        this.$modal.msgError("请选择要打印的数据");
      }
    },
    printCancel() {
      this.printOpen = false
    },
    // 详情
    handleView(row) {
      this.reset()
      this.resetForm('personnelForm')
      const id = row.id
      getPersonDetail(id).then(response =>{
        this.personnelForm = response.data
        this.changeStoreName();
        this.isShowView = true
        this.isShow = false
        this.title = '人员出入库详情'
        this.open = true
      })
    },
    // 修改
    handleUpdate(row) {
      this.reset()
      this.resetForm('personnelForm')
      const id = row.id
      getPersonDetail(id).then(response =>{
        this.personnelForm = response.data
        this.changeStoreName();
        this.isShowView = false
        this.isShow = true
        this.title = "修改信息"
        this.open = true
      })
    },
    // 删除
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除数据？').then(function () {
        return deletePerson(id)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 重置表单
    reset() {
      this.personnelForm = {
        storeId: undefined,
        manager: undefined,
        inTime: undefined,
        outTime: undefined,
        comeUser: undefined,
        userInfo: undefined,
        muDi: undefined,
        jieDai: undefined
      }
      this.$nextTick(() => {
        this.$refs.textareaRef.$refs.textarea.style.height = 'auto'; // 重置高度
      });
    },
    // 弹窗取消
    personnelCancel() {
      this.open = false
      this.managerOption = []
    },
    // 保存
    submitForm() {
      this.$refs["personnelForm"].validate(valid => {
        if (valid) {
          if(this.personnelForm.id != undefined) {
            const arr = this.storeNameOption.filter(item => item.value == this.personnelForm.storeId)
            this.personnelForm.storeName = arr[0].label
            console.log(this.personnelForm)
            updatePerson(this.personnelForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.managerOption = []
              this.getList();
            })
          } else {
            const arr = this.storeNameOption.filter(item => item.value == this.personnelForm.storeId)
            this.personnelForm.storeName = arr[0].label
            console.log(this.personnelForm)
            addPerson(this.personnelForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.managerOption = []
              this.getList();
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

::v-deep .el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
</style>
